/* eslint-disable */
import React, { useEffect, useRef, useState } from 'react';
import { Divider, Button, Card, Form, Row, Col, Input, Select, message, DatePicker, Popover, InputNumber, Spin } from 'antd';
import styles from './index.less';
import ApprovalHistoryModal from '../../components/common/approvalHistoryModal';
import OrganizationChooseRadio1 from '../../components/common/OrganizationChooseRadio1';
import SalesOrderModal from '../../components/common/SalesOrderModal';
import { momentSwitch, tableData, formatNoFixed, reservedDecimalPlace, debounce } from '../../utils/commonUtil';
import CreditFileManagementModal from '../../components/credit/creditFileManagement/CreditFileManagementModal';
import CreditEvaluationCreate from '../../components/credit/creditEvaluation/CreditEvaluationCreate';
import {
  insertCreditPayment, queryCustomerTypeInfo, updateCredit, submitCredit, searchFormDetail, getCreditIndicator, getAllDictionaryValueNotPage, getCreditRate
} from '../../services/quotaAccount/server';
import { connect } from 'dva';
import moment from 'moment';
import DetailTable from './detailTable';
import { EllipsisOutlined, SearchOutlined } from '@ant-design/icons';
import img from "../../assets/logo-loading.gif"
const { Search, TextArea } = Input;
const { Option } = Select;
const FormItem = Form.Item;

const Index = props => {
  const { onCancel, isEdit, quotaAccountId, showAdd, detaileData, onUpload, quotaModel, dispatch, globalModel, assessment, submit, edit, changestatus, complete } = props;
  const { fromList, examinationApprovalStatus, orgChooseList } = quotaModel;
  const { userInfo } = globalModel;
  const [lineType, setLineType] = useState('');
  const [statusCode, setStatusCode] = useState('');
  const [customerTypeFlag, setCustomerTypeFlag] = useState('');
  const [receiptNumber, setReceiptNumber] = useState('');
  const [editId, setEditId] = useState(null);
  const [accountAgeColumns, setAccountAgeColumns] = useState([
    { title: '归属机构', dataIndex: 'ownerShipInstitution', key: 'ownerShipInstitution' },
    { title: '账龄总额（元）', dataIndex: 'totalAmountCredit', key: 'totalAmountCredit' },
  ]);
  const [accountAgeList, setAccountAgeList] = useState([]);
  const [editDetaileData, setEditDetaileData] = useState(null);
  const [isDisabled, setIsDisabled] = useState(false);
  const [form] = Form.useForm();
  const approvalRef = useRef();
  const sRef = useRef();
  const oRef = useRef();
  const [creditFiles, useCreditFiles] = useState(false);
  const [creditEvaluation, useCreditEvaluation] = useState(false);
  const [indicatorList, setIndicatorList] = useState([]);
  const [creditEvaluationFlag, useCreditEvaluationFlag] = useState(false);
  const [spinFlag, useSpinFlag] = useState(false)

  useEffect(() => {
    if (showAdd) {
      if (quotaAccountId) {
        setEditId(quotaAccountId)
        getQueryCreditById(quotaAccountId);
      } else if (detaileData) {
        modifyData(detaileData);
      }
    }
  }, [showAdd, detaileData]);

  const getIndicator = code => {
    getCreditIndicator({
      ownerShipInstitutionCode: code,
    }).then(res => {
      if (res.code == 200) {
        setIndicatorList(res.data);
        console.log(res.data)
        res.data.map(item => {
          if (item.category) {
            getAllDictionaryValueNotPage({ dictCode: item.category }).then(res => {
              dispatch({
                type: 'quotaModel/updateState',
                payload: { [item.category]: res.data },
              });
            });
          }
        });
      }
    });
  };

  const getQueryCreditById = data => {
    searchFormDetail({ id: data, type: 2 }).then(res => {
      if (res.code == 200) {
        modifyData(res.data);
      } else {
        message.error("额度及账期详情查询失败");
        useSpinFlag(false)
      }
    });
  };

  const modifyData = data => {
    if (data) {
      if (changestatus == 'credit_pass') data.tbCreditPaymentBasicInformation.statusCode = changestatus
      getIndicator(data.tbCreditPaymentBasicInformation.ownerShipInstitutionCode);
      setTableColums(data);
      let { tbCreditPaymentBasicInformation, transactionCreditAccount, creditIndicatorList, tbTransactionInformation } = data;
      let { lineType, statusCode, receiptNumber, } = tbCreditPaymentBasicInformation;
      let { customerType } = tbTransactionInformation;

      setLineType(lineType);
      setStatusCode(statusCode);
      setReceiptNumber(receiptNumber);
      setCustomerTypeFlag(customerType)
      if (statusCode == 'credit_new' || statusCode == 'credit_reject') {
        setIsDisabled(false);
      } else {
        setIsDisabled(true);
      }
      // 自定义表单新增栏位（单行列表）
      fromList.forEach(item => {
        if (item.styleColumn == 2) {
          if (data[item.headerColumn]) {
            form.setFieldsValue(
              momentSwitch(fromList, data[item.headerColumn][0], item.headerColumn),
            );
          }
        }
        if (item.styleColumn == 1) {
          form.setFieldsValue(momentSwitch(fromList, data[item.headerColumn], item.headerColumn));
        }
      });
      // 账龄
      if (transactionCreditAccount && transactionCreditAccount.expressionFieldList) {
        let _accountAgeColumns = accountAgeColumns;
        let _accountAgeList = accountAgeList;
        let obj = {
          ownerShipInstitution: transactionCreditAccount.ownerShipInstitution,
          totalAmountCredit: transactionCreditAccount.totalAmountCredit,
        };
        transactionCreditAccount.expressionFieldList.forEach(item => {
          _accountAgeColumns.push({ title: item.key, dataIndex: item.key, key: item.key });
          obj[item.key] = item.value;
        });
        _accountAgeList = [obj];
        setAccountAgeList(_accountAgeList);
        setAccountAgeColumns(JSON.parse(JSON.stringify(_accountAgeColumns)));
      }
      //业务特征
      if (creditIndicatorList) {
        creditIndicatorList.map(item => {
          form.setFieldsValue({ [item.variable]: item.value });
        })
      }
      setEditDetaileData(JSON.parse(JSON.stringify(data)));

      let formData = form.getFieldsValue().transactionName
      if (formData.includes('大学') || formData.includes('学院') || formData.includes('实验') || formData.includes('试验场') ||
        formData.includes('研究') && formData !== '重庆康佳光电技术研究院有限公司' || typeof formData == 'number' || !isNaN(formData)) {
        useCreditEvaluationFlag(true)
      }
      useSpinFlag(false)
    }
  };

  const setTableColums = data => {
    fromList.forEach(item => {
      if (item.styleColumn == 3) {
        const dataSource = tableData(fromList, data, item.id);
        dispatch({
          type: 'quotaModel/updateState',
          payload: { [item.headerColumn]: dataSource },
        });
      }
    });
  };

  const onSave = submit => {
    let data = editDetaileData;
    form.validateFields().then(values => {
      for (let key in values) {
        //统一处理日期格式的文本值
        if (values[key] && values[key]._isAMomentObject) {
          values[key] = moment(values[key]).format('YYYY-MM-DD');
        }
      }

      fromList.map(item => {
        if (item.headerColumn) {
          if (item.styleColumn == 1) {
            item.activeFieldList.map(i => {
              if (values[i.columnValue]) {
                data[item.headerColumn][i.columnValue] = values[i.columnValue];
              }
            });
            if (values.orderNumber) {
              data.tbCreditPaymentBasicInformation.orderNumber = values.orderNumber;
            }
            if (values.ownerShipInstitutionCode) {
              data.tbCreditPaymentBasicInformation.ownerShipInstitutionCode =
                values.ownerShipInstitutionCode;
            }
            if (values.esMonthAvgTransactionVolume) {
              data.tbTransactionInformation.esMonthAvgTransactionVolume =
                values.esMonthAvgTransactionVolume;
            }
          } else if (item.styleColumn == 2) {
            //单行列表的数据从form里面取出来封装成对象
            data[item.headerColumn] = [{}];
            item.activeFieldList.map(i => {
              if (values[i.columnValue]) {
                data[item.headerColumn][0][i.columnValue] = values[i.columnValue] || [];
              }
            });
          } else if (item.styleColumn == 3) {
            //多行列表直接去modal里面取
            data[item.headerColumn] = quotaModel[item.headerColumn] || [];
          }
        }
      });
      let _indicatorList = indicatorList;
      _indicatorList.map(item => {
        item.value = values[item.variable];
      });
      data.creditIndicatorList = _indicatorList;
      if (editId) {
        editId ? data.tbCreditPaymentBasicInformation.id = editId : null
        editId ? data.tbTransactionInformation.id = editId : null
        data.tbCreditPaymentBasicInformation.receiptNumber = receiptNumber
        updateCredit({ map: data, type: 2 }).then(res => {
          if (res.code == 200) {
            if (submit) {
              onSubmit({ id: editId, receiptNumber });
            } else {
              message.success('编辑成功');
              getQueryCreditById(editId);
            }
          } else {
            message.error("编辑失败");
            useSpinFlag(false)
          }
        });
      } else {
        insertCreditPayment({ map: data, type: 2 }).then(res => {
          if (res.code == 200) {
            setReceiptNumber(res.data.receiptNumber);
            setEditId(res.data.id);
            if (submit) {
              onSubmit(res.data);
            } else {
              message.success('新建成功');
              getQueryCreditById(res.data.id);
            }
          } else {
            message.error("新建失败");
            useSpinFlag(false)
          }
        });
      }
    }).catch(error => { useSpinFlag(false) });
  };

  const onSubmit = data => {
    submitCredit({ ...data, flag: statusCode == 'credit_new' || statusCode == 'credit_reject' ? 1 : 2, }).then(res => {
      if (res.code == 200) {
        message.success('操作成功');
        getQueryCreditById(data.id);
      } else if (res.code == 400) {
        message.warning(res.message);
        useSpinFlag(false)
      }
    });
  };

  const orderSave = (selectedRowKeys, selectedRows) => {
    form.setFieldsValue({ orderNumber: selectedRows[0].orderNumber });
  };

  const onSelect = (value, option, item) => {
    if (item.columnValue == 'lineType') {
      setLineType(value);
    } else if (item.columnValue == 'ownerShipInstitution') {
      form.setFieldsValue({
        ownerShipInstitutionCode: value,
        ownerShipInstitution: option.children,
      });
    } else if (item.columnValue == 'customerType') {
      setCustomerTypeFlag(value)
    }
  };

  const getText = item => {
    switch (item.columnType) {
      case '1':
        let data = ['existCreditLine', 'applyCredit', "registerCapital", "turnoverOneYear", "averageTradeTwelve"]
        if (data.indexOf(item.columnValue) > -1) {
          return (
            <InputNumber placeholder={item.whetherEditor == 0 ? `请输入 ${item.columnName}` : ''} style={{ width: "100%" }}
              formatter={value => value ? formatNoFixed(reservedDecimalPlace(value, 2)) : ''} disabled={isDisabled || item.whetherEditor == 1} />
          )
        } else {
          return (
            <Input
              placeholder={item.whetherEditor == 0 ? `请输入 ${item.columnName}` : ''}
              disabled={isDisabled || item.whetherEditor == 1}
            />
          );
        }
      case '2':
        if (item.columnValue == 'ownerShipInstitution') {
          return (
            <Search autoComplete="off" onSearch={() => { oRef.current.show(); }} onClick={() => { oRef.current.show(); }} disabled={isDisabled || item.whetherEditor == 1} />
          );
        } else {
          return (
            <Select
              disabled={
                isDisabled || item.whetherEditor == 1 || item.columnValue == 'approvalStatus'
              }
              placeholder={item.whetherEditor == 0 ? `请选择${item.columnName}` : ''}
              onSelect={(value, option) => {
                onSelect(value, option, item);
              }}
            >
              {quotaModel[item.code] &&
                quotaModel[item.code].map((i, index) => (
                  <Option key={i.dictSubCode} value={i.dictSubCode}>
                    {i.dictValue}
                  </Option>
                ))}
            </Select>
          );
        }
      case '3':
        return (
          <DatePicker
            placeholder={item.whetherEditor == 0 ? `请输入${item.columnName}` : ''}
            disabled={isDisabled || item.whetherEditor == 1}
            style={{ width: '100%' }}
          />
        );
      case '4':
        return (
          <Input
            placeholder={item.whetherEditor == 0 ? `请输入${item.columnName}` : ''}
            disabled={isDisabled || item.whetherEditor == 1}
          />
        );
      case '5':
        return (
          <TextArea
            placeholder={`请输入${item.columnName}`}
            disabled={isDisabled || item.whetherEditor == 1}
          />
        );
      default:
        return <div></div>;
    }
  };

  //归属机构
  const orgOnSave = (key, rows) => {
    form.setFieldsValue({
      ownerShipInstitution: rows[0].orgName,
      ownerShipInstitutionCode: rows[0].orgCode,
    });
    getIndicator(rows[0].orgCode);
    queryCustomerTypeInfo({
      masterDataCode: editDetaileData.tbTransactionInformation.masterDataCode,
      orgCode: rows[0].orgCode,
    }).then(res => {
      form.setFieldsValue({
        customerType: res.data ? res.data.customerTypeCode : null,
      })
      setCustomerTypeFlag(res.data ? res.data.customerTypeCode : null)
    });
  };

  const popoverContent = () => {
    return (
      <div className={styles.popover_content}>
        <div onClick={() => onUpload(form.getFieldsValue(), editId)}>附件上传及查看</div>
        <div onClick={() => useCreditFiles(true)}>查看信用档案</div>
        <div
          onClick={() => {
            approvalRef.current.show(receiptNumber);
          }}
        >
          审批历史记录查询
        </div>
      </div>
    );
  };

  const creditFileManagementModalProps = {
    operateType: 'view',
    masterDataCode:
      editDetaileData && editDetaileData.tbTransactionInformation
        ? editDetaileData.tbTransactionInformation.masterDataCode
        : null,
    onCancel: () => useCreditFiles(false),
  };

  const creditEvaluationCreateProps = {
    operateType: 'add',
    creditEvaluation,
    creditEvaluationInfoData: {
      assessmentStatus: 'credit_evaluation_new',
      createTime: moment(new Date()).format('YYYY-MM-DD'),
      createId: JSON.parse(userInfo).id,
      createName: JSON.parse(userInfo).userName,
      quotaAccountId: editId,
      counterpartyName:
        editDetaileData && editDetaileData.tbTransactionInformation
          ? editDetaileData.tbTransactionInformation.transactionName
          : null,
      masterDataCode:
        editDetaileData && editDetaileData.tbTransactionInformation
          ? editDetaileData.tbTransactionInformation.masterDataCode
          : null,
      affiliatedInstitution: form.getFieldsValue().ownerShipInstitutionCode,
      affiliatedInstitutionName: form.getFieldsValue().ownerShipInstitution,
    },
    examinationApprovalStatus,
    orgChooseList,
    customerTypeFlag,
    creditEvaluationFlagTrue: true,
    onCancel: () => useCreditEvaluation(false),
  };

  const completeAssessment = () => {
    let formData = form.getFieldsValue()
    if (formData.transactionName.includes('大学') || formData.transactionName.includes('学院') || formData.transactionName.includes('实验') ||
      formData.transactionName.includes('试验场') || formData.transactionName.includes('研究') && formData.transactionName !== '重庆康佳光电技术研究院有限公司' ||
      typeof formData.transactionName == 'number' || !isNaN(formData.transactionName)) {
      onSave(true)
    } else {
      getCreditRate({
        masterDataCode: formData.masterDataCode,
        affiliatedInstitution: formData.ownerShipInstitutionCode,
      }).then(prop => {
        if (prop.code == 200) {
          if (prop.data == 'E') {
            useSpinFlag(false);
            message.error("该客户评级为E，不允许发生授信交易");
          } else {
            onSave(true)
          }
        } else {
          message.warning(prop.message);
          useSpinFlag(false);
        }
      })
    }
  }

  const debounceAddFun = debounce(onSave, 1000)
  const debounceCompleteFun = debounce(completeAssessment, 1000)

  return (
    <div>
      {creditFiles && <CreditFileManagementModal {...creditFileManagementModalProps} />}
      {creditEvaluation && <CreditEvaluationCreate {...creditEvaluationCreateProps} />}
      {!creditFiles && !creditEvaluation && (
        <Spin spinning={spinFlag} indicator={<div style={{ height: "50px", width: "37px", top: "40%", margin: "-30px" }}>
          <img src={img}></img>
        </div>}>
          <Card style={{ marginBottom: '16px' }}>
            <div className={styles.toolbarText} style={{ marginBottom: '0' }}>
              <div>额度及账期{isEdit ? '查看' : '申请'}</div>
              <div style={{ display: 'flex' }}>
                <Button style={{ borderRight: 'none' }} onClick={() => useCreditEvaluation(true)}
                  disabled={assessment || (statusCode !== 'credit_evaluate' && statusCode !== 'credit_reject') || creditEvaluationFlag}> 信用评估 </Button>
                <Popover content={popoverContent} trigger="hover" placement="bottomRight">
                  <Button >
                    <EllipsisOutlined />
                  </Button>
                </Popover>
                <Button style={{ margin: '0 15px' }} onClick={onCancel}> 返回</Button>
                <Button style={{ marginRight: '15px' }} onClick={() => { useSpinFlag(true); debounceAddFun(false) }} disabled={(isEdit && edit) || isDisabled}>保存</Button>
                {/* 没有保存直接点击提交按钮 */}
                {
                  (statusCode == 'credit_new' || statusCode == 'credit_reject') ?
                    (<Button type="primary" onClick={() => { useSpinFlag(true); debounceAddFun(true) }} disabled={(isEdit && edit) || submit}>提交评估</Button>) :
                    (<Button type="primary" onClick={() => { useSpinFlag(true); debounceCompleteFun() }}
                      disabled={(isEdit && edit) || statusCode !== 'credit_evaluate' || complete}>完成评估</Button>)
                }
              </div>
            </div>
          </Card>
          <Card>
            <Form form={form} layout={'vertical'}>
              {fromList.map((item, index) => item.whetherHidden != 1 && (
                <div key={index + "fromList"}>
                  <Divider orientation="left">{item.headerName}</Divider>
                  {item.styleColumn == 1 && (<Row gutter={20}>
                    {item.activeFieldList.map((it, ins) => it.whetherEnable == 0 && it.columnType !== '5' && (
                      <Col span={8} key={ins + "styleColumnOne"}>
                        <FormItem label={it.columnValue == 'enterpriseNature' && !isEdit ? '企业类型' : it.columnName}
                          name={it.columnValue} rules={[{ required: it.whetherLose == 0, message: `请输入${it.columnName}`, },]} >
                          {getText(it)}
                        </FormItem>
                      </Col>))}
                    {item.headerColumn == 'tbTransactionInformation' && customerTypeFlag == "customerType_new" && (
                      <Col span={8} >
                        <FormItem
                          label="预计月均交易额"
                          name={'esMonthAvgTransactionVolume'}
                          rules={[{ required: true }]}
                        >
                          <InputNumber placeholder="预计月均交易额" style={{ width: "100%" }} formatter={value => value ? formatNoFixed(value,) : ''}
                            disabled={(isEdit && edit) || isDisabled} />
                        </FormItem>
                      </Col>
                    )}
                    {item.headerColumn == 'tbCreditPaymentBasicInformation' && (
                      <Col span={0}>
                        <FormItem
                          name={'ownerShipInstitutionCode'}
                          rules={[{ required: true }]}
                        >
                          <Input />
                        </FormItem>
                      </Col>
                    )}
                    {lineType == 'single_line' &&
                      item.headerColumn == 'tbCreditPaymentBasicInformation' && (
                        <Col span={8}>
                          <FormItem label="销售订单号" name={'orderNumber'} rules={[{ required: true, message: '请选择销售订单号' }]}>
                            <Search autoComplete="off" onSearch={() => sRef.current.show()} onClick={() => sRef.current.show()} disabled={(isEdit && edit) || isDisabled} />
                          </FormItem>
                        </Col>
                      )}
                    {item.activeFieldList.map((it, ins) => it.whetherEnable == 0 && it.columnType == '5' && (
                      <Col span={24} key={ins + "styleColumnTwo"}>
                        <FormItem label={it.columnValue == 'enterpriseNature' && !isEdit ? '企业类型' : it.columnName}
                          name={it.columnValue} rules={[{ required: it.whetherLose == 0, message: `请输入${it.columnName}`, },]} >
                          {getText(it)}
                        </FormItem>
                      </Col>
                    ))}
                  </Row>)}
                  {item.styleColumn == 1 && item.headerColumn == 'tbCreditPaymentBasicInformation' && indicatorList.length > 0 && (
                    <Divider orientation="left">业务特征属性</Divider>
                  )}
                  {item.styleColumn == 1 && item.headerColumn == 'tbCreditPaymentBasicInformation' && (<Row gutter={20}>
                    {
                      indicatorList.map((t, i) => (
                        <Col span={8} key={i + "indicatorList"}>
                          <FormItem label={t.pname} name={t.variable}>
                            {t.category ? (
                              <Select disabled={(isEdit && edit) || isDisabled}>
                                {quotaModel[t.category] &&
                                  quotaModel[t.category].map(i => (
                                    <Option key={i.dictSubCode} value={i.dictValue}>
                                      {i.dictValue}
                                    </Option>
                                  ))}
                              </Select>
                            ) : (
                              <Select disabled={(isEdit && edit) || isDisabled}>
                                <Option value="1" > 是 </Option>
                                <Option value="0" > 否 </Option>
                              </Select>
                            )}
                          </FormItem>
                        </Col>
                      ))
                    }
                  </Row>)}
                  {item.styleColumn == 2 && (
                    <Row style={{ border: '1px solid #e8e8e8' }}>
                      {item.activeFieldList.map((it, ins) => it.whetherEnable == 0 && (
                        <Col
                          span={12}
                          key={ins + "activeFieldList"}
                          style={{ display: 'flex', borderBottom: '1px solid #e8e8e8' }}
                        >
                          <Col span={12} className={styles.contantLineLeft}>
                            {it.columnName}
                          </Col>
                          <Col span={12} className={styles.contantLineRight}>
                            <FormItem name={it.columnValue} rules={[{ required: it.whetherLose == 0, message: `请输入${it.columnName}`, },]} >
                              {getText(it)}
                            </FormItem>
                          </Col>
                        </Col>
                      ))}
                    </Row>
                  )}
                  {item.styleColumn == 3 && (
                    <DetailTable item={item} />
                  )}
                </div>
              ))}
            </Form>
          </Card>
        </Spin>
      )}
      <ApprovalHistoryModal approvalRef={approvalRef} />
      <SalesOrderModal sRef={sRef} onSave={orderSave} editDetaileData={editDetaileData} />
      <OrganizationChooseRadio1 oRef={oRef} onSave={orgOnSave} orgChooseList={orgChooseList} />
    </div>
  );
};

function mapStateToProps({ quotaModel, globalModel }) {
  return { quotaModel, globalModel };
}

export default connect(mapStateToProps)(Index);
